<template>
	<view class="login-wrap">
		<u-navbar :bgColor="'transparent'">
			<view @click="toHome" slot="left" style="display: flex;flex-direction: column;justify-content: center;align-items: center;">
				<image  src="/static/tabbar/home2.png" style="width: 48rpx;height: 48rpx;"></image>
				<view style="font-size: 20rpx;color: #9d9d9d;">回到首页</view>
			</view>
		</u-navbar>
		<div class="login-form" :style="{
      backgroundImage: 'url(' + loginBgUrl + ')',
      backgroundRepeat: 'no-repeat',
      backgroundPosition: 'center',
      backgroundSize: '100% 100%'
    }">
			<div class="logo">
				<image :src="logoUrl" mode=""></image>
				<p>萧岗租房</p>
			</div>
			<div class="login-button">
				<button class="shouquan" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"> 手机号快捷登录 </button>
				<p class="quxiao" @click="cancelLogin">取消登录</p>
			</div>
			<div class="xieyi">
				<checkbox-group @change="checkboxChange">
					<checkbox value="agree" color="#0095F8" style="transform: scale(0.7)" :checked="checked" /> 我已阅读且同意萧岗小程序 <span
						style="color: #0095f8" @click="toDetail('yinsi')"> 《隐私保护指引》 </span> 和 <span style="color: #0095f8"
						@click="toDetail('xieyi')"> 《用户协议》 </span>
				</checkbox-group>
			</div>
		</div>
		<uni-popup ref="popup" type="dialog">
			<uni-popup-dialog mode="base" @close="close" @confirm="confirm">
				<div class="sqdl">
					<image v-if="formData.avatar" :src="formData.avatar" mode="widthFix"></image>
					<image v-else src="/static/mine/avatar.png" mode="widthFix"></image>
					<button open-type="chooseAvatar" @chooseavatar="getUserProfile"> 点击获取头像 </button>
					<input type="nickname" maxlength="20" v-model="formData.username" placeholder="点击获取昵称"
						@change="handleChange" />
				</div>
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>
<script>
	import {
		mapGetters
	} from "vuex";
	import {
		updateUserInfo
	} from "@/api/mine.js";
	export default {
		data() {
			return {
				hasUserInfo: false,
				agree: "1",
				loginInfo: {},
				myUserInfo: {},
				checked: false,
				logoUrl: this.$Config.HTTP_REQUEST_URL + "/zufang/logo.png",
				// 动态背景图地址，从配置域名获取
				loginBgUrl: this.$Config.HTTP_REQUEST_URL + "/zufang/loginbg.png",
				formData: {
					username: "",
					avatar: "",
				},
			};
		},
		computed: mapGetters(["isLogin", "uid", "userInfo"]),
		onLoad() {},
		methods: {
			toHome(){
				uni.reLaunch({
					url:'/pages/index/index'
				})
			},
			checkboxChange(e) {
				if (e.detail.value.length == 0) {
					this.checked = false;
				} else {
					this.checked = true;
				}
			},
			// 获取手机号授权
			getPhoneNumber(e) {
				if (this.checked) {
					console.log(e.detail.code); // 动态令牌
					console.log(e.detail.errMsg); // 回调信息（成功失败都会返回）
					console.log(e.detail.errno); // 错误码（失败时返回）
					if (e.detail.errno == "104") {
						uni.showToast({
							title: "同意才能授权登录！",
							icon: "none",
							duration: 3000,
						});
						return false;
					}
					// e.detail.errMsg 两种不同的返回结果 是不同机型的缘故
					if (e.detail.errMsg == "getPhoneNumber:fail user deny" || e.detail.errMsg == "getPhoneNumber:fail:user deny") {
						return;
					}
					uni.showLoading({
						mask: true,
					});
					const jsCode = e.detail.code;
					if (jsCode == undefined || jsCode == null || jsCode == "") {
						uni.showToast({
							title: "授权登录失败，请使用验证码登录！",
							icon: "none",
							duration: 3000,
						});
						return false;
					}
					this.login(jsCode);
				} else {
					uni.showToast({
						title: "请同意相关协议",
						icon: "none",
					});
				}
			},
			// 登录并获取用户信息
			login(jsCode) {
				uni.login({
					provider: "weixin",
					success: (loginRes) => {
						// 登录成功，获取用户code
						const {
							code
						} = loginRes;
						// 发送code到后台换取openId, sessionKey, unionId
						uni.request({
							url: `${this.$Config.HTTP_REQUEST_URL}/api/user/mpLogin`, // 你的登录API地址
							method: "POST",
							data: {
								code,
								phone_code: jsCode,
							},
							success: (res) => {
								console.log(res, "ressddaataa");
								uni.hideLoading();
								if (res.data.code === 1) {
									console.log(res.data.data);
									// 将用户信息和session存储到本地
									uni.setStorageSync("userInfo", res.data.data.userinfo);
									const isHttps = /^https:\/\//i.test(res.data.data.userinfo.avatar);
									if (isHttps) {
										uni.switchTab({
											url: "/pages/mine/mine",
										});
									} else {
										this.$refs.popup.open();
									}
								} else {
									uni.showToast({
										title: "登录失败",
										icon: "none",
									});
								}
							},
							fail: () => {
								uni.showToast({
									title: "请求失败",
									icon: "none",
								});
							},
						});
					},
					fail: (err) => {
						console.log("uni.login 接口调用失败，将无法正常使用开放接口等服务", err);
						uni.showToast({
							title: "登录失败",
							icon: "none",
						});
					},
				});
			},
			getUserProfile(e) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: this.$Config.HTTP_REQUEST_URL + "/api/common/ossUpload", // 仅为示例，非真实的接口地址
						filePath: e.detail.avatarUrl,
						name: "file",
						formData: {
							file: e.detail.avatarUrl,
						},
						header: {
							token: uni.getStorageSync("userInfo").token,
						},
						success: (res) => {
							if (res.statusCode === 200) {
								this.formData.avatar = JSON.parse(res.data).code.fullurl;
							}
						},
					});
				});
			},
			handleChange(e) {
				// console.log(e, 'eeesssaa');
				this.formData.username = e.detail.value.trim();
			},
			async updateUserInfo() {
				console.log(this.formData, "this.formData");
				const res = await updateUserInfo(this.formData);
				if (res.response.statusCode === 200) {
					uni.switchTab({
						url: "/pages/mine/mine",
					});
				}
			},
			confirm() {
				console.log(this.formData, "this.formData");
				this.updateUserInfo();
			},
			cancelLogin() {
				uni.switchTab({
					url: "/pages/mine/mine",
				});
			},
			toDetail(type) {
				uni.navigateTo({
					url: "/pages/mine/guideDetail?type=" + type,
				});
			},
		},
	};
</script>
<style lang="scss" scoped>
	.login-wrap {
		width: 100%;
		height: 100vh;
		background-color: #fcfeff;

		.login-form {
			width: 100%;
			height: 100vh;
			// height: 812px;
			background-size: 100% 100%;

			/* 背景由模板内联样式设置，移除写死的 url */
			.logo {
				width: 100px;
				margin: 0 auto;
				padding: 200px 0 56px 0;
				text-align: center;

				image {
					width: 64px;
					height: 64px;
				}

				p {
					font-family: PingFangSC, PingFang SC;
					font-weight: 600;
					font-size: 24px;
					color: #054187;
					line-height: 33px;
				}
			}

			.login-button {
				.shouquan {
					width: 311px;
					height: 47px;
					background: #0095f8;
					box-shadow: 0px 2px 4px 0px rgba(0, 149, 248, 0.5);
					border-radius: 22px;
					text-align: center;
					line-height: 47px;
					font-weight: 500;
					font-size: 15px;
					color: #ffffff;
					margin: 0 auto 16px auto;
				}

				.quxiao {
					width: 311px;
					height: 47px;
					background: #ffffff;
					box-shadow: 0px 2px 4px 0px rgba(0, 149, 248, 0.05);
					border-radius: 25px;
					font-weight: 400;
					font-size: 15px;
					color: #5d87b4;
					line-height: 47px;
					text-align: center;
					margin: 0 auto;
				}
			}

			.xieyi {
				padding-top: 16px;
				text-align: center;
				color: #666666;
				font-size: 13px;
			}
		}

		.sqdl {
			margin: auto;

			image {
				width: 60px;
				height: 60px;
				border-radius: 60px;
				display: block;
				margin: 10px auto;
			}

			input {
				border: 1px solid #eee;
				padding: 10px;
				margin: 10px auto;
			}

			// button{
			// 	width: 60px;
			// 	height: 60px;
			// }
		}
	}
</style>